package com.agent.crm.view;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import xu.ye.view.GroupContactActivity;
import xu.ye.view.HomeContactActivity;
import xu.ye.view.TypeContactActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;

import com.agent.crm.base.BaseActivity;
import com.agent.crm.bean.NoteBookDomain;
import com.agent.crm.db.NoteBookDao;
import com.pwp.activity.CalendarActivity;
import com.pwp.activity.CalendarWeekActivity;
import com.pwp.activity.ContactAttentionActivity;
import com.pwp.activity.ScheduleInfoView;

public class NoteBookActivity extends BaseActivity {
	
	private Button btn_contact;
	private Button title_bt_setting;
	private Button btn_carlendar;
	private Button btn_search;
	private Button note_book;
	private Button btn_attention;
	
	private ListView list ;
	private Button bt_add;
	
	private int yearTemp;
	private int monthTemp;
	private int dayTemp;
	private int hourTemp;
	private int minuteTemp;
	int itemSelectID;
	LinearLayout layoutView;
	boolean time_picker_flag=false;
	
	List<HashMap<String,String>> data =new ArrayList<HashMap<String,String>>() ;
	SimpleAdapter adapter ;
	NoteBookDao dao =new NoteBookDao(NoteBookActivity.this);
	
	private void searchAllNotes(){
		List<NoteBookDomain> notes=dao.getAllNoteBook();
		data.clear();
		for (int i = 0; i < notes.size(); i++) {
			HashMap<String, String> map=new HashMap<String, String>();
			map.put("note_gaiyao", String.valueOf("标题："+notes.get(i).getNoteItemTitle())+"\n"+"内容："+notes.get(i).getNoteItemTitleContent()+"\n"+"截止时间："+notes.get(i).getNoteItemLimitDate());
			map.put("noteBook_id", String.valueOf(notes.get(i).getNoteBookId()));
			map.put("noteItemTitle", notes.get(i).getNoteItemTitle());
			map.put("noteItemTitleContent", notes.get(i).getNoteItemTitleContent());
			map.put("noteItemLimitDate", notes.get(i).getNoteItemLimitDate());
			data.add(map);
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
        switch (v.getId()) {
		case R.id.bt_add_contacts:
			AlertDialog.Builder builder =new AlertDialog.Builder(this);
			layoutView =new LinearLayout(this);
			LayoutInflater inflater =LayoutInflater.from(this);
			inflater.inflate(R.layout.add_node, layoutView);
			layoutView.findViewById(R.id.save_note).setVisibility(View.GONE);
			(layoutView.findViewById(R.id.noteDate)).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					final Calendar c= Calendar.getInstance();
			        c.setTime(new Date());
					yearTemp =c.get(Calendar.YEAR);
					monthTemp=c.get(Calendar.MONTH);
					dayTemp=c.get(Calendar.DAY_OF_MONTH);
					hourTemp= c.get(Calendar.HOUR_OF_DAY);
					minuteTemp=c.get(Calendar.MINUTE);
					new DatePickerDialog(NoteBookActivity.this, new OnDateSetListener() {
						
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							// TODO Auto-generated method stub
							yearTemp =year;
							monthTemp=monthOfYear;
							dayTemp=dayOfMonth;
							TimePickerDialog time_dialog=new TimePickerDialog(NoteBookActivity.this, new OnTimeSetListener() {
								
								@Override
								public void onTimeSet(TimePicker view, int hourOfDay, int min) {
									time_picker_flag=false;
									hourTemp=hourOfDay;
									minuteTemp=min;
									((TextView)layoutView.findViewById(R.id.noteDate)).setText(yearTemp+"-"+((monthTemp+1)<10?("0"+(monthTemp+1)):(monthTemp+1))+"-"+dayTemp+" "+hourTemp+":"+minuteTemp);
								}
							},hourTemp,minuteTemp, true);
							if(!time_picker_flag){
								time_dialog.show();
								time_picker_flag=true;
							}
						}
					},yearTemp,monthTemp,dayTemp).show();
				}
			});
			
			
			builder.setTitle("新增记事")
			       .setView(layoutView)
			       .setPositiveButton("保存", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							NoteBookDomain note =new NoteBookDomain();
							if( "".equalsIgnoreCase(((EditText)layoutView.findViewById(R.id.noteTitle)).getText().toString())||
								null==((EditText)layoutView.findViewById(R.id.noteTitle)).getText().toString()||
								"".equalsIgnoreCase(((EditText)layoutView.findViewById(R.id.noteContent)).getText().toString())||
								null==((EditText)layoutView.findViewById(R.id.noteContent)).getText().toString()||
								"".equalsIgnoreCase(((TextView)layoutView.findViewById(R.id.noteDate)).getText().toString())||
								null==((TextView)layoutView.findViewById(R.id.noteDate)).getText().toString()){
								showSimpleAlertDialog("请将，标题、内容和时间填写完整");
								return;
							}
							note.setNoteItemTitle(((EditText)layoutView.findViewById(R.id.noteTitle)).getText().toString());
							note.setNoteItemTitleContent(((EditText)layoutView.findViewById(R.id.noteContent)).getText().toString());
							note.setNoteItemLimitDate(((TextView)layoutView.findViewById(R.id.noteDate)).getText().toString());
							dao.save(note);
							searchAllNotes();
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				}).show();
			break;
		case R.id.schedule_and_carlendar:
			Intent intent = new Intent();
            SharedPreferences preferences =getSharedPreferences("scheduleStatusMode", Context.MODE_PRIVATE);
            String lunchMode =preferences.getString("CalendarDefaultLunchMode", "WeekCalendar");
            if (lunchMode.equalsIgnoreCase("DayCalendar")) {
            	Date date = new Date();
    	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    	    	String currentDate = sdf.format(date);  //当期日期
    	    	String year_c = currentDate.split("-")[0];
    	    	String month_c = currentDate.split("-")[1];
    	    	String day_c = currentDate.split("-")[2];
    	    	Calendar car=Calendar.getInstance();
    	    	car.setTime(new Date());
    	    	ArrayList<String> scheduleDate = makeScheduleDate(year_c, month_c, day_c,car.get(Calendar.DAY_OF_WEEK)-1);
                intent.putStringArrayListExtra("scheduleDate", scheduleDate);
            	intent.setClass(this, ScheduleInfoView.class);
			}else if(lunchMode.equalsIgnoreCase("WeekCalendar")) {
				intent.setClass(this, CalendarWeekActivity.class);
			}else if(lunchMode.equalsIgnoreCase("MonthCalendar")) {
				intent.setClass(this, CalendarActivity.class);
			}
            startActivity(intent);
			break;
		case R.id.search_contact_schedule:
            Intent intent_search = new Intent();
            intent_search.setClass(this, SearchActivity.class);
            startActivity(intent_search);
			break;
        case R.id.contact:
            Intent contactIntent = new Intent();
            contactIntent.setClass(this, MainActivity.class);
            startActivity(contactIntent);
            break;
        case R.id.attention_contact:
            Intent aatentionIntent = new Intent();
            aatentionIntent.setClass(this, ContactAttentionActivity.class);
            startActivity(aatentionIntent);
            break;
		default:
			break;
		}
	}

	public ArrayList<String> makeScheduleDate(String scheduleYear,String scheduleMonth,String scheduleDay,int position){
		String week = "";
		//得到这一天是星期几
        switch(position%7){
        case 0:
      	  week = "星期日";
      	  break;
        case 1:
      	  week = "星期一";
      	  break;
        case 2:
      	  week = "星期二";
      	  break;
        case 3:
      	  week = "星期三";
      	  break;
        case 4:
      	  week = "星期四";
      	  break;
        case 5:
      	  week = "星期五";
      	  break;
        case 6:
      	  week = "星期六";
      	  break;
        }
		 
        ArrayList<String> scheduleDate = new ArrayList<String>();
        scheduleDate.add(scheduleYear);
        scheduleDate.add(scheduleMonth);
        scheduleDate.add(scheduleDay);
        scheduleDate.add(week);
        //scheduleDate.add(scheduleLunarDay);
        return scheduleDate;
	}
	
	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.note_book;
	}

	@Override
	protected View initCustomLayout() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViewCmp() {
		// TODO Auto-generated method stub
		btn_contact=(Button)findViewById(R.id.contact);
		btn_carlendar=(Button)findViewById(R.id.schedule_and_carlendar);
		btn_search=(Button)findViewById(R.id.search_contact_schedule);
		note_book=(Button)findViewById(R.id.note_book);
		note_book.setBackgroundResource(R.drawable.home_btn_bg_d);
		btn_attention = (Button)findViewById(R.id.attention_contact);
		((TextView)findViewById(R.id.title_txt)).setText("记事本");
		
		title_bt_setting=(Button)findViewById(R.id.title_bt_setting);
		title_bt_setting.setVisibility(View.GONE);
		list =(ListView)findViewById(R.id.note_book_list);
		bt_add =(Button)findViewById(R.id.bt_add_contacts);
		adapter =new SimpleAdapter(this, data, R.layout.note_book_list_item, new String[]{"note_gaiyao","noteItemTitle","noteItemTitleContent","noteItemLimitDate"}, new int[]{R.id.note_gaiyao,R.id.noteTitle,R.id.noteContent,R.id.noteDate});
		list.setAdapter(adapter);
		searchAllNotes();
	}

	@Override
	protected void initListener() {
		// TODO Auto-generated method stub
		bt_add.setOnClickListener(this);
		btn_contact.setOnClickListener(this);
		btn_carlendar.setOnClickListener(this);
		btn_search.setOnClickListener(this);
		btn_attention .setOnClickListener(this);
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				itemSelectID=arg2;
				AlertDialog.Builder builder=new AlertDialog.Builder(NoteBookActivity.this);
				builder.setTitle("请选择操作").setItems(new String[]{"查看记事","修改记事","删除记事"}, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case 0:
							AlertDialog.Builder b =new AlertDialog.Builder(NoteBookActivity.this);
							LinearLayout layoutView =new LinearLayout(NoteBookActivity.this);
							LayoutInflater inflater =LayoutInflater.from(NoteBookActivity.this);
							inflater.inflate(R.layout.add_node, layoutView);
							layoutView.findViewById(R.id.save_note).setVisibility(View.GONE);
							((EditText)layoutView.findViewById(R.id.noteTitle)).setText(data.get(itemSelectID).get("noteItemTitle"));
							((EditText)layoutView.findViewById(R.id.noteContent)).setText(data.get(itemSelectID).get("noteItemTitleContent"));
							((TextView)layoutView.findViewById(R.id.noteDate)).setText(data.get(itemSelectID).get("noteItemLimitDate"));
							b.setTitle("查看记事")
						     .setView(layoutView)
						     .setPositiveButton("確定", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									
								}
							}).show();
							break;
						case 1:
							AlertDialog.Builder b2 =new AlertDialog.Builder(NoteBookActivity.this);
							final LinearLayout layoutView2 =new LinearLayout(NoteBookActivity.this);
							LayoutInflater inflater2 =LayoutInflater.from(NoteBookActivity.this);
							inflater2.inflate(R.layout.add_node, layoutView2);
							layoutView2.findViewById(R.id.save_note).setVisibility(View.GONE);
							((EditText)layoutView2.findViewById(R.id.noteTitle)).setText(data.get(itemSelectID).get("noteItemTitle"));
							((EditText)layoutView2.findViewById(R.id.noteContent)).setText(data.get(itemSelectID).get("noteItemTitleContent"));
							((TextView)layoutView2.findViewById(R.id.noteDate)).setText(data.get(itemSelectID).get("noteItemLimitDate"));
							(layoutView2.findViewById(R.id.noteDate)).setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									final Calendar c= Calendar.getInstance();
							        c.setTime(new Date());
									yearTemp =c.get(Calendar.YEAR);
									monthTemp=c.get(Calendar.MONTH);
									dayTemp=c.get(Calendar.DAY_OF_MONTH);
									hourTemp= c.get(Calendar.HOUR_OF_DAY);
									minuteTemp=c.get(Calendar.MINUTE);
									new DatePickerDialog(NoteBookActivity.this, new OnDateSetListener() {
										
										@Override
										public void onDateSet(DatePicker view, int year, int monthOfYear,
												int dayOfMonth) {
											// TODO Auto-generated method stub
											yearTemp =year;
											monthTemp=monthOfYear;
											dayTemp=dayOfMonth;
											TimePickerDialog time_dialog=new TimePickerDialog(NoteBookActivity.this, new OnTimeSetListener() {
												
												@Override
												public void onTimeSet(TimePicker view, int hourOfDay, int min) {
													time_picker_flag=false;
													hourTemp=hourOfDay;
													minuteTemp=min;
													((TextView)layoutView2.findViewById(R.id.noteDate)).setText(yearTemp+"-"+((monthTemp+1)<10?("0"+(monthTemp+1)):(monthTemp+1))+"-"+dayTemp+" "+hourTemp+":"+minuteTemp);
												}
											},hourTemp,minuteTemp, true);
											if(!time_picker_flag){
												time_dialog.show();
												time_picker_flag=true;
											}
										}
									},yearTemp,monthTemp,dayTemp).show();
								}
							});
							b2.setTitle("修改记事")
						     .setView(layoutView2)
						     .setPositiveButton("保存", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									NoteBookDomain note =new NoteBookDomain();
									if( "".equalsIgnoreCase(((EditText)layoutView2.findViewById(R.id.noteTitle)).getText().toString())||
										null==((EditText)layoutView2.findViewById(R.id.noteTitle)).getText().toString()||
										"".equalsIgnoreCase(((EditText)layoutView2.findViewById(R.id.noteContent)).getText().toString())||
										null==((EditText)layoutView2.findViewById(R.id.noteContent)).getText().toString()||
										"".equalsIgnoreCase(((TextView)layoutView2.findViewById(R.id.noteDate)).getText().toString())||
										null==((TextView)layoutView2.findViewById(R.id.noteDate)).getText().toString()){
										showSimpleAlertDialog("请将，标题、内容和时间填写完整");
										return;
									}
									note.setNoteBookId(Integer.valueOf(data.get(itemSelectID).get("noteBook_id")));
									note.setNoteItemTitle(((EditText)layoutView2.findViewById(R.id.noteTitle)).getText().toString());
									note.setNoteItemTitleContent(((EditText)layoutView2.findViewById(R.id.noteContent)).getText().toString());
									note.setNoteItemLimitDate(((TextView)layoutView2.findViewById(R.id.noteDate)).getText().toString());
									dao.update(note);
									searchAllNotes();
								}
							}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									
								}
							}).show();
							break;
						case 2:
							dao.delete(data.get(itemSelectID).get("noteBook_id"));
							searchAllNotes();
							break;
						default:
							break;
						}
					}
				}).show();
			}
		});
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initAsycnData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void changeDefaultSetting() {
		// TODO Auto-generated method stub

	}
	
	

}
